package org.huis.common.security.interceptor;

import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.huis.common.core.constants.HttpConstants;
import org.huis.common.security.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
/**
 * @author huis
 * @date 2024/8/28 20:07
 */
@Component // 把这个bean交给system微服务管理，从system的配置中可以获得“${jwt.secret}”
public class TokenInterceptor implements HandlerInterceptor {
    @Value("${jwt.secret}")
    private String secret; //从哪个服务的配置文件中获取，取决于这个bean对象交给那个服务的spring容器进行管理

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = getToken(request);
        tokenService.extendToken(token ,secret);
        return true;
    }

    private String getToken(HttpServletRequest request){
        String token = request.getHeader(HttpConstants.AUTHENTICATION);
        if(StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)){
            token = token.replaceFirst(HttpConstants.PREFIX,"");
        }
        return token;
    }
}
